package com.shuangk.majingze.coolpapa.presenter;

import android.util.Log;

import com.shuangk.majingze.coolpapa.contract.user.LoginContract;
import com.shuangk.majingze.coolpapa.http.RetrofitClient;
import com.shuangk.majingze.coolpapa.http.apiservice.CoolService;
import com.shuangk.majingze.coolpapa.model.User;
import com.shuangk.majingze.coolpapa.utils.CheckUtils;
import com.shuangk.majingze.coolpapa.utils.LogUtils;
import com.shuangk.majingze.coolpapa.utils.MD5Utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


public class LoginPresenterImpl implements LoginContract.Presenter {

    LoginContract.View view;

    public LoginPresenterImpl(LoginContract.View view) {
        this.view = view;
        view.setPresenter(this);
    }

    @Override
    public void start() {
        login();
    }

    @Override
    public void login() {
        //登录
        final User user = view.getUser();
        String username = user.getUsername();
        String pwd = MD5Utils.MD5(user.getPassword());
        if (CheckUtils.isUsername(username) && CheckUtils.isPassword(pwd)) {
            view.showMessage("请输入正确的用户名和密码");
            return;
        }
        user.setPassword(pwd);
        CoolService coolService = RetrofitClient.getInstance(view.getContext(), "http://tcc.taobao.com")
                .getService();
        Map<String, String> params = new HashMap<>();
        params.put("tel", "15211168600");
        coolService.remote(params)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Log.d("LoginPresenter",responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }
}
